/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;
using Gtk;

namespace Whitemice.ZOGI.GtkFolios
{
  //TODO: Implement drop support;  but where to drag from?
	[System.ComponentModel.Category("widget")]
	[System.ComponentModel.ToolboxItem(true)]
	public class ObjectLinkTab : Gtk.ScrolledWindow, IEntityForm, IZOGIWidget
	{
		protected Viewport				                    viewport;
		
		public 		EntityEventHandler	                OnEntityPresent;
    public 		EntityEventHandler	                OnLinkDelete;
    
    protected MultiResultCallback                callback;
		
		public ObjectLinkTab() : base()
		{
		  OnEntityPresent = null;
		  OnLinkDelete = null;
		  this.callback = new MultiResultCallback(this.ReceiveDataCallback);
			this.HscrollbarPolicy = PolicyType.Automatic;
			this.VscrollbarPolicy = PolicyType.Always;
			viewport = new Viewport();
			this.Child = viewport;
			TargetEntry[] target = new TargetEntry[] {
			  new TargetEntry("LINK",  TargetFlags.OtherApp, 1)
			};
			Gtk.Drag.DestSet(this, 
			  DestDefaults.Highlight, 
			  target, 
			  Gdk.DragAction.Copy);
		} /* End Constrkuctor */
		
		/// <summary>
		/// Filling this tab only adds a loading links or no links label.
		/// All the targets or sources of the links are queried from the
		/// server to ensure they are in the cache.  When that search
		/// calls back the object-links froms will actually be created.
		/// </summary>
		/// <param name="entity">
		/// A <see cref="Whitemice.ZOGI.Entity"/>
		/// </param>
		public void Fill(Entity entity)
		{
			IEnumerable<Whitemice.ZOGI.ObjectLink>  links;
									
			Clear();
			links = entity.Links;
			if (links.Count() > 0)
			{
				IList<int>  targets;
        FetchCommand  command;

        targets = new List<int>();
			  viewport.Child = new Label("Loading links...");
			  foreach(ObjectLink link in links)
			  {
			    int           candidate;
			    
			    if (link.TargetId == entity.ObjectId)
			      candidate = link.SourceId;
			    else candidate = link.TargetId;
			    if (!(targets.Contains(candidate)))
			      targets.Add(candidate);
        }
        command = new FetchCommand(targets, RpcPriority.Immediate, null, 0, new object[] { "multi-fill", links, entity} );
        command.Callback = callback;
        Server.Connection.RunCommand(command);
 	    } else
 	      {
 	        viewport.Child = new Label("No links for object");
 	      }
			ShowAll();
		} // end Fill
		
		public void Clear()
		{
			if (!(viewport.Child == null))
				viewport.Remove(viewport.Child);		
		}	/* end Clear */
    
		/// <summary>
		/// Data has come back from the server so all the objects referenced by
		/// links should be in the cache.  Now we proceed to assemble the forms
		/// and push them into the form.
		/// </summary>
    public void ReceiveRPCCall(RPCEventArgs args)
		{
      object[]  context;
      
      if (args.Context is Array)
      {
        context = (object[])args.Context;
      } else return;

      switch(context[0].ToString())
      {
        case "multi-fill":
          var entity = (context[2] as Whitemice.ZOGI.Entity);
          var links = (context[1] as IEnumerable<Whitemice.ZOGI.ObjectLink>);
          int c = 0;
          ObjectLinkForm  olf;
          VBox v = new VBox();
          v.Spacing = 2;
          foreach(Whitemice.ZOGI.ObjectLink link in links)
          {
            if (link.Kind != "Preferred Job Executant")
            {
              this.ZLOG(string.Format("Creating summary for link#{0}", link.ObjectId));
              olf = new Whitemice.ZOGI.GtkWidgets.ObjectLinkForm(entity);
              olf.OnEntityPresent = this.OnEntityPresent;
              olf.OnLinkDelete = this.OnLinkDelete;
              olf.Fill(link);
              if ((c % 2) == 1)
                olf.BackgroundColor = GUI.ColorForKey("oddRowBackground");
              else
                olf.BackgroundColor = GUI.ColorForKey("evenRowBackground");
              v.PackStart(olf, false, false, 2);
              c++;
            }
          }
          Clear();
          viewport.Child = v;
          viewport.ShowAll();          
       break;
      }
		} /* end ReceiveData */
		
		public new void DragDataReceived(object o, DragDataReceivedArgs args)
		{
		  this.ZLOG(string.Format("ObjectLink tab received {0}", o.GetType()));
		}
	}
}